﻿using Bird.Core;
using Bird.Core.Data;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bird.Data
{
    public class EfRepository<TEntity> :IQueryable<TEntity>, IRepository<TEntity> where TEntity : BaseEntity
    {
        public IDbSet<TEntity> Entities { get; private set; }
        public IDbContext DbContext { get; private set; }
        public EfRepository(IDbContext context)
        {
            this.Entities = context.Entities<TEntity>();
            this.DbContext = context;
        }

        public TEntity GetById(object id)
        {
            return Entities.Find(id);
        }





        public void Insert(TEntity entity)
        {
            this.Entities.Add(entity);
            this.DbContext.SaveChanges();
        }

        public void Update(TEntity entity)
        {
            this.DbContext.SaveChanges();
        }

        public void Delete(TEntity entity)
        {
            this.Entities.Remove(entity);
        }

        public IQueryable<TEntity> Table
        {
            get { return this.Entities; }
        }


        public IEnumerator<TEntity> GetEnumerator()
        {
            return Table.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return Table.GetEnumerator();
        }

        public Type ElementType
        {
            get { return Table.ElementType; }
        }

        public System.Linq.Expressions.Expression Expression
        {
            get { return Table.Expression; }
        }

        public IQueryProvider Provider
        {
            get { return Table.Provider; }
        }
    }
}
